package com.qf.day09.work2;

import java.util.Arrays;

public class BookImpl implements BookInterface{
    private Book[] books = new Book[5];
    private Book book;

    private int count = 0;

    public Book[] getBooks() {
        return books;
    }

    public void setBooks(Book[] books) {
        this.books = books;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public BookImpl() {
    }

    @Override
    public boolean addBook(Book book) {

        for (int i = 0; i <this.getCount(); i++) {
            if(book.getBookName().equals(this.books[i].getBookName())){
                return false;
            }
        }
        if(count == books.length){
            //数组扩容
            books = Arrays.copyOf(books , books.length*2);
        }
        books[count++] = book;
        return true;
    }

    @Override
    public boolean updateBook(Book book) {
        if(count<=0){
            return false;
        }
        books[count-1] = book;
        return true;

    }

    @Override
    public boolean deleteBook(String bookId) {
        if(selectOne(bookId) == null){
            return false;
        }

        int id = Integer.parseInt(bookId);
        for (int i = 0; i < count; i++) {
            if(id == books[i].getPid()){
                for (int j = i; j <count ; j++) {
                    books[j] = books[j+1];
                }
               count--;
            }

        }
        return true;
    }

    @Override
    public Book selectOne(String bookId) {
        int id = Integer.parseInt(bookId);
        for (int i = 0; i < count; i++) {
            if(id == books[i].getPid()){
                return books[i];
            }
        }
        return null;
    }

    @Override
    public Book[] selectAll() {
        return books;
    }
}
